package net.vistiyos.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class FilesTubeAdapter {
	// Database fields
		private static final String ID_FIELD="idquery";
		private static final String QUERY_FIELD="query";
		private static final String DB_TABLE = "historial";
		private Context context;
		private SQLiteDatabase db;
		private FilesTubeDBHelper dbHelper;

		public FilesTubeAdapter(Context context) {
			this.context = context;
		}

		public FilesTubeAdapter open() throws SQLException {
			dbHelper = new FilesTubeDBHelper(context);
			db = dbHelper.getWritableDatabase();
			return this;
		}

		public void close() {
			dbHelper.close();
		}

		/**
		 * Create a new todo If the todo is successfully created return the new
		 * rowId for that note, otherwise return a -1 to indicate failure.
		 */
		public long createTodo(String query) {
			ContentValues values = createContentValues(query);
			return db.insert(DB_TABLE, null, values);
		}

		/**
		 * Update the todo
		 */
		public boolean updateTodo(long rowId,String query) {
			ContentValues values = createContentValues(query);
			return db.update(DB_TABLE, values, ID_FIELD + "=" + rowId, null) > 0;
		}

		/**
		 * Deletes todo
		 */
		public boolean deleteTodo(long rowId) {
			return db.delete(DB_TABLE, ID_FIELD + "=" + rowId, null) > 0;
		}

		/**
		 * Return a Cursor over the list of all todo in the database
		 * 
		 * @return Cursor over all notes
		 */
		public Cursor fetchAllTodos() {
			return db.query(DB_TABLE, new String[] { ID_FIELD, QUERY_FIELD }, null, null, null, null, null);
		}

		/**
		 * Return a Cursor positioned at the defined todo
		 */
		public Cursor fetchTodo(long rowId) throws SQLException {
			Cursor mCursor = db.query(true, DB_TABLE, new String[] { ID_FIELD,QUERY_FIELD }, ID_FIELD + "=" + rowId, null, null, null, null, null);
			if (mCursor != null) {
				mCursor.moveToFirst();
			}
			return mCursor;
		}

		private ContentValues createContentValues(String query) {
			ContentValues values = new ContentValues();
			values.put(QUERY_FIELD, query);
			return values;
		}
		
		public boolean exists(String query){
			return db.rawQuery("select * from historial where query='"+query+"'", null).getCount()==1;
		}
}
